package top.meeting.room.module.system.services.impl;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheKit;
import top.jfinal.jwtTokenPlugin.kit.JwtKit;
import top.meeting.room.common.constant.ResultEnum;
import top.meeting.room.common.exceptions.HandlerException;
import top.meeting.room.common.kit.ListKit;
import top.meeting.room.module.system.form.RoleForm;
import top.meeting.room.module.system.model.Role;
import top.meeting.room.module.system.query.RoleQuery;
import top.meeting.room.module.system.services.IRoleService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 我有故事，你有酒么？
 * JKhaled created by yunqisong@foxmail.com 2017/7/22
 * FOR : 角色服务接口实现
 */
public class RoleService implements IRoleService {

    public static final IRoleService me = new RoleService();

    private RoleService() {
    }

    public Page<Role> pageModel(RoleQuery roleQuery) {
        Page<Role> retVal = null;
        if (roleQuery == null)
            throw new HandlerException(ResultEnum.DATA_ERROR, "查询参数不可以为空");
        retVal = CacheKit.get(Role.role_pageModel, String.valueOf(roleQuery));
        if (retVal == null) {
            SqlPara sqlPara = Role.dao.getSqlPara(Role.role_pageModel, Kv.by("text", roleQuery.getText()));
            sqlPara.setSql(sqlPara.getSql().replaceFirst(" AND ", " WHERE "));
            retVal = Role.dao.paginate(roleQuery.getPage() == null ? 1 : roleQuery.getPage(),
                    roleQuery.getSize() == null ? 10 : roleQuery.getSize(), sqlPara);
            CacheKit.put(Role.role_pageModel, String.valueOf(roleQuery), retVal);
        }
        return retVal;
    }

    public Page<Record> pageRecord(RoleQuery roleQuery) {
        Page<Record> retVal = null;
        if (roleQuery == null)
            throw new HandlerException(ResultEnum.DATA_ERROR, "查询参数不可以为空");
        retVal = CacheKit.get(Role.role_pageRecord, String.valueOf(roleQuery));
        if (retVal == null) {
            Page<Role> rolePage = pageModel(roleQuery);
            retVal = new Page<Record>(rolePage.getList().stream().map(role -> {
                return role.toBack();
            }).collect(Collectors.toList()), rolePage.getPageNumber(), rolePage.getPageSize(), rolePage.getTotalPage(), rolePage.getTotalRow());
            CacheKit.put(Role.role_pageRecord, String.valueOf(roleQuery), retVal);
        }

        return retVal;
    }

    @Override
    public Role getModel(Long id) {
        Role retVal = CacheKit.get(Role.role_getModel, String.valueOf(id));
        if (retVal == null) {
            retVal = Role.dao.findById(id);
            CacheKit.put(Role.role_getModel, String.valueOf(id), retVal);
        }
        return retVal;
    }

    @Override
    public Record getRecord(Long id) {
        Record retVal = CacheKit.get(Role.role_getRecord, String.valueOf(id));
        if (retVal == null) {
            Role role = getModel(id);
            retVal = role == null ? null : role.toBack();
            CacheKit.put(Role.role_getRecord, String.valueOf(id), retVal);
        }
        return retVal;
    }

    @Override
    public Role saveAsModel(RoleForm roleForm) {
        isAllowed(roleForm);
        // TODO:暂时允许修改超级管理员权限
//        if(roleForm.getId() == 1){
//            throw new HandlerException(ResultEnum.DB_ERROR,"无权修改超级管理员的权限");
//        }
        if (roleForm.getId() == null && findByRoleName(roleForm.getRoleName()) != null)
            throw new HandlerException(ResultEnum.DB_ERROR, "不要添加重复的角色");
        Role role = null;
        role = new Role().setRoleName(roleForm.getRoleName())
                .setForces(JSONObject.toJSONString(roleForm.getForces()));
        if (roleForm.getId() != null)
            role.setId(roleForm.getId()).update();
        else
            role.save();
        remove();
        return role;
    }

    public Role saveDepartment(RoleForm roleForm) {
        if (roleForm.getId() == null && findByRoleName(roleForm.getRoleName()) != null)
            return null;
        Role role = null;
        role = new Role().setRoleName(roleForm.getRoleName());
        if (roleForm.getId() != null)
            role.setId(roleForm.getId()).update();
        else
            role.save();
        remove();
        return role;
    }

    public Role findByRoleName(String roleName) {
        Role role = CacheKit.get(Role.role_findByRoleName, roleName);
        if (role == null) {
            SqlPara sqlPara = Db.getSqlPara(Role.role_findByRoleName, roleName);
            role = Role.dao.findFirst(sqlPara.getSql(), roleName);
            CacheKit.put(Role.role_findByRoleName, roleName, role);
        }
        return role;
    }

    private void isAllowed(RoleForm roleForm) {
        if (roleForm == null)
            throw new HandlerException(ResultEnum.DATA_ERROR, "上传表单数据错误");
    }

    public Record saveAsRecord(RoleForm roleForm) {
        return null;
    }

    public void deleteById(Long id) {
        deleteByIds(String.valueOf(id));
        remove();
    }

    public void deleteByIds(String ids) {
        List<Long> idList = ListKit.ids2List(ids);
        if (idList.contains(1L))
            throw new HandlerException(ResultEnum.DATA_ERROR, "不可以删除超级管理员");
        SqlPara sqlPara = Db.getSqlPara(Role.role_deleteByIds, Kv.by("ids", idList));
        Db.update(sqlPara.getSql(), sqlPara.getPara());
        remove();
    }

    public void remove() {
        CacheKit.removeAll(Role.role_getModel);
        CacheKit.removeAll(Role.role_getRecord);
        CacheKit.removeAll(Role.role_getForces);
        CacheKit.removeAll(Role.role_pageModel);
        CacheKit.removeAll(Role.role_pageRecord);
        CacheKit.removeAll(Role.role_getForceIds);
        CacheKit.removeAll(Role.role_findByRoleName);

        // 更新用户信息
        JwtKit.storeReset();
        UserService.me.remove();
    }

}
